package com.rongke.sms;


import com.alibaba.fastjson.JSONObject;
import com.rongke.utils.RandomUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by bilibili on 2017/8/10.
 */
public class SmsUtils {



    private static final String SHOPAAPPKEY = "ed8dc93a24e228c0dbe65a250e1be2fd";
    private static final String SHOPAPPSECRET = "239de6b15d90";



    // 计算并获取CheckSum
    public static String getCheckSum(String appSecret, String nonce, String curTime) {
        return encode("sha1", appSecret + nonce + curTime);
    }

    // 计算并获取md5值
    public static String getMD5(String requestBody) {
        return encode("md5", requestBody);
    }

    private static String encode(String algorithm, String value) {
        if (value == null) {
            return null;
        }
        try {
            MessageDigest messageDigest
                    = MessageDigest.getInstance(algorithm);
            messageDigest.update(value.getBytes());
            return getFormattedText(messageDigest.digest());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    private static String getFormattedText(byte[] bytes) {
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        for (int j = 0; j < len; j++) {
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
        }
        return buf.toString();
    }
    private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

    /**
     * 校验验证码
     * @param phone 手机号码
     * @param code  验证码
     * @param userType 用户类型，2表示骑手，3表示商家
     * @return true表示成功，false表示失败
     * @throws Exception
     */
    public static Boolean checkCode(String phone,String code,Integer userType) throws Exception {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String url = "https://api.netease.im/sms/verifycode.action";
        HttpPost httpPost = new HttpPost(url);

        String appKey;
        String appSecret;

            appKey = SHOPAAPPKEY;
            appSecret = SHOPAPPSECRET;

        String nonce = RandomUtils.getRandomString(8);
        String curTime = String.valueOf((new Date()).getTime() / 1000L);
        String checkSum = getCheckSum(appSecret, nonce ,curTime);//参考 计算CheckSum的java代码

        // 设置请求的header
        httpPost.addHeader("AppKey", appKey);
        httpPost.addHeader("Nonce", nonce);
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("CheckSum", checkSum);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

        // 设置请求的参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("mobile", phone));
        nvps.add(new BasicNameValuePair("code", code));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));

        // 执行请求
        HttpResponse response = httpClient.execute(httpPost);

        // 打印执行结果
        JSONObject obj = JSONObject.parseObject(EntityUtils.toString(response.getEntity(), "utf-8"));
        System.out.println(obj.toJSONString());

        if("200".equals(obj.get("code").toString())){
            return  true;
        }else{
            return  false;
        }

    }

    /**
     * 发送验证码
     * @param phone 电话号码
     * @param userType 用户类型，2表示骑手，3表示商家
     *@param  templateid  验证码模板id （可无）
     * @return
     * @throws Exception
     */
    public static String sendCode(String phone,Integer userType, String templateid) throws Exception {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String url = "https://api.netease.im/sms/sendcode.action";
        HttpPost httpPost = new HttpPost(url);

        String appKey;
        String appSecret;

        appKey = SHOPAAPPKEY;
        appSecret = SHOPAPPSECRET;

        String nonce = RandomUtils.getRandomString(8);
        String curTime = String.valueOf((new Date()).getTime() / 1000L);
        String checkSum = getCheckSum(appSecret, nonce ,curTime);//参考 计算CheckSum的java代码

        // 设置请求的header
        httpPost.addHeader("AppKey", appKey);
        httpPost.addHeader("Nonce", nonce);
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("CheckSum", checkSum);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

        // 设置请求的参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("mobile", phone));
        if(!"".equals(templateid)){
            nvps.add(new BasicNameValuePair("templateid", templateid));
        }
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));

        // 执行请求
        HttpResponse response = httpClient.execute(httpPost);

        // 打印执行结果
        JSONObject obj = JSONObject.parseObject(EntityUtils.toString(response.getEntity(), "utf-8"));
        System.out.println(obj.toJSONString());
        if("200".equals(obj.get("code").toString())){
            return obj.get("code").toString();
        }else{
            return  "";
        }
    }

    /**
     * 发送短信
     * @param phones 手机号码
     * @param templateid  模板id
     * @param params (可无)
     * @param userType 用户类型，2表示骑手，3表示商家
     * @return true表示成功，false表示失败
     * @throws Exception
     */
    public static Boolean sendMsg(JSONArray phones, String templateid, JSONArray params, Integer userType) throws Exception {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String url = "https://api.netease.im/sms/sendtemplate.action";
        HttpPost httpPost = new HttpPost(url);
        String appKey;
        String appSecret;

        appKey = SHOPAAPPKEY;
        appSecret = SHOPAPPSECRET;
        String nonce = RandomUtils.getRandomString(8);
        String curTime = String.valueOf((new Date()).getTime() / 1000L);
        String checkSum = getCheckSum(appSecret, nonce ,curTime);//参考 计算CheckSum的java代码
        // 设置请求的header
        httpPost.addHeader("AppKey", appKey);
        httpPost.addHeader("Nonce", nonce);
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("CheckSum", checkSum);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        // 设置请求的参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("templateid", templateid));
        nvps.add(new BasicNameValuePair("mobiles", phones.toString()));
        if(params!=null){
            nvps.add(new BasicNameValuePair("params", params.toString()));
        }
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
        // 执行请求
        HttpResponse response = httpClient.execute(httpPost);
        // 打印执行结果
        JSONObject obj = JSONObject.parseObject(EntityUtils.toString(response.getEntity(), "utf-8"));
        System.out.println(obj.toJSONString());
        if("200".equals(obj.get("code").toString())){
            return  true;
        }else{
            return  false;
        }

    }

    /**
     * 发送多个短信
     * @param phones 手机号码
     * @param templateid  模板id
     * @param params (可无)
     * @param userType 用户类型，2表示骑手，3表示商家
     * @return true表示成功，false表示失败
     * @throws Exception
     */
    public static Boolean sendManyMsg(JSONArray phones, String templateid, String params, Integer userType) throws Exception {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String url = "https://api.netease.im/sms/sendtemplate.action";
        HttpPost httpPost = new HttpPost(url);
        String appKey;
        String appSecret;
        appKey = SHOPAAPPKEY;
        appSecret = SHOPAPPSECRET;
        String nonce = RandomUtils.getRandomString(8);
        String curTime = String.valueOf((new Date()).getTime() / 1000L);
        String checkSum = getCheckSum(appSecret, nonce ,curTime);//参考 计算CheckSum的java代码
        // 设置请求的header
        httpPost.addHeader("AppKey", appKey);
        httpPost.addHeader("Nonce", nonce);
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("CheckSum", checkSum);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        // 设置请求的参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("templateid", templateid));
        nvps.add(new BasicNameValuePair("mobiles", phones.toString()));
        if(params!=null){
            nvps.add(new BasicNameValuePair("params", params.toString()));
        }
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
        // 执行请求
        HttpResponse response = httpClient.execute(httpPost);
        // 打印执行结果
        JSONObject obj = JSONObject.parseObject(EntityUtils.toString(response.getEntity(), "utf-8"));
        System.out.println(obj.toJSONString());
        if("200".equals(obj.get("code").toString())){
            return  true;
        }else{
            return  false;
        }

    }


    public static void main(String[] args) throws Exception {
        JSONArray phones=new JSONArray();
        phones.put("18337102204");
       /* phones.put("15257119142");
        phones.put("13754320574");*/
        sendMsg(phones,"3056315",null,2);
    }


}
